<template>
  <el-card>
    <div slot="header">
      <h3>潜在验收标准-新增（横版）</h3>
    </div>
    <div>
      <BtnRender :render="renderBtnsBar" />
      <UmyTable
        showActionCol
        :tableHeight="480"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :actionRender="renderTableBtnAction"
        @handleRowInputModify="handleRowInputModify"
      />
    </div>
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateSkusBySeniorLinked"
    />
    <AccumulationAssociate
      :visible.sync="associateGoods.visible"
      :form-items="associateGoods.formItems"
      :columns="associateGoods.columns"
      :load-data="loadAssociateGoodsData"
      @update="updateSkusByAssociateGoods"
    />
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import UmyTable from '@/components/UmyTable';
import InputNumber from '@/components/inputNumber/inputNumber';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import AccumulationAssociate from '@/components/AssociateGoods/Accumulation';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import {
  createExcelByExport,
  generateUuid,
  isResponseSuccess,
} from '@/utils/bizUtils';
import {
  getVerticalChangeValue,
  getVerticalNewColKey,
} from './utils';
import {
  ASSOCIATE_FORM_ITEMS,
  ASSOCIATE_TABLE_COLUMNS,
} from './constants/horizontalEdit';
import {
  EDIT_TABLE_COLUMNS,
  EDIT_TABLE_CHILDREN_COLUMNS1,
  EDIT_TABLE_CHILDREN_COLUMNS2,
} from './constants'
import {
  getSkuInfoWithPermissionService,
  getVerticalInitDataWithPermissionService,
  exportVerticalDataService,
  importVerticalDataUrl,
  saveVerticalDataService,
} from '@api/commodity/temporaryPurchasingGoods/acceptanceStandard';
export default {
  name: 'HorizontalEdit', // 批量维护验收标准（横版）
  components: {
    BtnRender,
    UmyTable,
    InputNumber,
    SeniorLinkedDialog,
    AccumulationAssociate,
  },
  data () {
    return {
      skuNos: [],
      TableInfo: new TableInfo({ columns: EDIT_TABLE_COLUMNS }),
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
      },
      associateGoods: {
        visible: false,
        formItems: ASSOCIATE_FORM_ITEMS,
        columns: ASSOCIATE_TABLE_COLUMNS,
      },
      btnLoading: {
        export: false, // 导出按钮loading
        submit: false, // 提交按钮loading
      }
    }
  },
  methods: {
    // 渲染表头按钮操作栏
    renderBtnsBar (h) {
      const btnList = [
        {
          label: '高级关联',
          method: this.handleSeniorLinked,
        },
        {
          label: '关联商品',
          method: this.handleAssociateGoods,
        },
        {
          label: '导出',
          method: this.handleExport,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.export
        },
        {
          label: '导入',
          action: importVerticalDataUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading
        },
        {
          label: '提交',
          method: this.handleSubmit,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.submit
        }
      ]
      return getListPageBtnsBar(h, btnList)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '删除', method: this.handleDelete }]
      return getTableAction({ h, row, actionList })
    },
    // 删除
    handleDelete (row) {
      const updateList = this.TableInfo.list.filter(item => item.skuNo != row.skuNo)
      this.TableInfo.setList(updateList)
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleAssociateGoods () {
      this.associateGoods.visible = true
    },
    // 导出
    async handleExport () {
      const data = { exportList: this.getSubmitList() }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportVerticalDataService(data, loadingFn)
      const uuid = generateUuid()
      createExcelByExport({ excelTitle: `潜在商品验收标准（横版）_${uuid}`, res })
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        const updateList = this.getUpdateDataList(res?.retData ?? [])
        this.TableInfo.setList(updateList)
        this.updateColumns(updateList[0])
      }
    },
    // 提交
    async handleSubmit () {
      const data = { commitList: this.getSubmitList() }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await saveVerticalDataService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$confirm('提交成功，点击确认关闭当前页面', '提示', {
          type: 'warning',
        }).then(() => {
          window.close()
        }).catch(() => {})
      }
    },
    // 加载关联商品集合
    loadAssociateGoodsData (configs) {
      const { formData, paginationParams, loadingFn } = configs ?? {}
      const data = {
        ...formData,
        ...paginationParams
      }
      return getSkuInfoWithPermissionService(data, loadingFn)
    },
    // 更新高级关联商品集合
    updateSkusBySeniorLinked (skuNos) {
      this.skuNos = _.uniq([...this.skuNos, ...skuNos])
      this.updateTableList()
    },
    // 更新关联商品集合
    updateSkusByAssociateGoods (skuVos) {
      const skuNos = skuVos.map(item => item.skuNo)
      this.skuNos = _.uniq([...this.skuNos, ...skuNos])
      this.updateTableList(skuNos)
    },
    // 更新表格数据
    async updateTableList () {
      this.TableInfo.setColumns(EDIT_TABLE_COLUMNS)
      const data = { skuNos: this.skuNos }
      const res = await getVerticalInitDataWithPermissionService(data, this.TableInfo.setLoading)
      if (!isResponseSuccess(res)) {
        this.skuNos = []
      }
      const updateList = this.getUpdateDataList(res?.retData ?? [])
      this.TableInfo.setList(updateList)
      this.updateColumns(updateList[0])
    },
    // 更新表列
    updateColumns (firstRow) {
      const newColumns = _.cloneDeep(EDIT_TABLE_COLUMNS)
      const detailList = firstRow?.detailList ?? [] // 表头，遍历第1行的动态列时，才追加到表头
      detailList.forEach((item, index) => {
        const children1 = EDIT_TABLE_CHILDREN_COLUMNS1.map(col => ({ ...col, key: getVerticalNewColKey({ col, index, row: item }) }))
        const children2 = EDIT_TABLE_CHILDREN_COLUMNS2.map(col => ({ ...col, key: getVerticalNewColKey({ col, index, row: item }) }))
        newColumns.push({
          title: item.checkItemName,
          required: item.isNeed == '1',
          key: item.checkItemUuid,
          width: 150,
          children: item.checkItemType != '2' ? children1 : children2,
        })
      })
      this.TableInfo.setColumns(newColumns)
    },
     // 获取更新源数据集合
     getUpdateDataList (sourceList) {
      const getFlatVos = detailList => {
        detailList = detailList ?? []
        const flatVos = detailList.reduce((value, item, index) => {
          value[getVerticalNewColKey({ key: 'checkCount', index, row: item })] = item.checkCount // 验收次数
          value[getVerticalNewColKey({ key: 'standardValue', index, row: item })] = item.standardValue // 标准值
          value[getVerticalNewColKey({ key: 'upDiffValue', index, row: item })] = item.upDiffValue // 上差值
          value[getVerticalNewColKey({ key: 'downDiffValue', index, row: item })] = item.downDiffValue // 下差值
          value[getVerticalNewColKey({ key: 'checkMethod', index, row: item })] = item.checkMethod // 验收方法
          value[getVerticalNewColKey({ key: 'checkItemType', index, row: item })] = item.checkItemType // 1数字5个列可填，2文本3个列可填
          return value
        }, {})
        return flatVos
      }
      const updateList = sourceList.map(item => ({
        ...item,
        ...getFlatVos(item.detailList)
      }))
      return updateList
    },
    // 获取提交导出参数
    getSubmitList () {
      const DETAIL_KEYS = ['checkCount', 'standardValue', 'upDiffValue', 'downDiffValue', 'checkMethod']
      const submitList = []
      const sourceList = _.cloneDeep(this.TableInfo.list)
      sourceList.forEach(row => {
        row.detailList.forEach((item ,index) => {
          DETAIL_KEYS.forEach(key => {
            item[key] = row[getVerticalNewColKey({ key, index, row: item })]
          })
        })
        submitList.push(row)
      })
      return submitList
    },
    // 行输入框修改
    handleRowInputModify ({ row, val, columnName }) {
      this.standardValChange({ row, val, columnName })
    },
    // 标准值变更逻辑
    standardValChange ({ row, val, columnName }) {
      const {
        upDiffValue,
        downDiffValue,
        upDiffKey,
        downDiffKey,
      } = getVerticalChangeValue({ row, val, columnName }) ?? {}
      if (upDiffKey) {
        row[upDiffKey] = upDiffValue
      }
      if (downDiffKey) {
        row[downDiffKey] = downDiffValue
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-divider--horizontal {
  margin: 12px 0;
}
</style>
